package com.oracleoaec.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
	private Socket socket = null;
	private BufferedReader bufr = null;
	private PrintWriter pw = null;
	
    /*请求，包括与客户端建立连接，发送一次请求，获取响应，断开连接
    context 要发送的请求内容 得到的响应字符串*/
	 
	public String request(String context) {
		String result = null;
		// 建立连接
		connect();
		// 写
		pw.println(context);
		try {
			// 读
			result = bufr.readLine();
		} catch (IOException e) {
			e.printStackTrace();
		}
		// 关闭连接
		close();
		return result;
	}

	
	//与服务器建立连接
	public void connect() {
		try {
			socket = new Socket("127.0.0.1", 5055);
			bufr = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			pw = new PrintWriter(socket.getOutputStream(), true);
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	
	//与服务器断开连接，释放资源
	public void close() {
		if (bufr != null) {
			try {
				bufr.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if (pw != null) {
			pw.close();
		}
		if (socket != null) {
			try {
				socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
